Welcome to pandas!

5.4时间戳转换

1、时间戳转换1

将不规范时间戳转为标准时间戳,是数据清洗工作中经常见到的,也是令人头痛的事, 不过pandas中的pd.to_datetime()函数很好的解决了这个问题,该函数既可以对单个数字、文本时间戳做转换, 也可以对存储在列表、数组等数据结构中的不规范时间戳做转换。


import pandas as pd

l1=[ "2021-3-3","2021-7-3 14:17:54","1999.02.13 07:25:09" ]

l2=[ "2/3/1995 12:34:43","5/6/1995 14:44:33","13/2/1995 07:25:09" ]

t1=pd.DatetimeIndex(l1) #pd.to_datetime(l2)会出错误

t2=pd.DatetimeIndex(l2) #pd.DatetimeIndex 返回的数据是一个时间序列

print (t1)

print (t2)

返回:

DatetimeIndex(['2021-03-03 00:00:00', '2021-07-03 14:17:54',

'1999-02-13 07:25:09'],

dtype='datetime64[ns]', freq=None)

DatetimeIndex(['1995-02-03 12:34:43', '1995-05-06 14:44:33',

'1995-02-13 07:25:09'],

dtype='datetime64[ns]', freq=None)


import pandas as pd

df=pd.read_excel(r "D:\Pyobject2023\object\测试\素材\素材测试.时间戳格式转换.xlsx" )

print (df)

t=df.通过日期.str.findall( "\d+" ).str.join( "-" )

print (t)

df[ "通过日期1" ]=pd.to_datetime(t)

# df[ "通过日期1" ]=pd.DatetimeIndex(t)#等同上面一行

print (df)

返回:

姓名 分数 通过日期
0 张三 89 2022年4月30日
1 李四 96 2021.5.18(补考通过)
2 王麻子 83 补考过:2011/11/11
3 小曾 99 第三次补考通过:2024-1-/12

0 2022-4-30
1 2021-5-18
2 2011-11-11
3 2024-1-12

Name: 通过日期, dtype: object

姓名 分数 通过日期 通过日期1
0 张三 89 2022年4月30日 2022-04-30
1 李四 96 2021.5.18(补考通过) 2021-05-18
2 王麻子 83 补考过:2011/11/11 2011-11-11
3 小曾 99 第三次补考通过:2024-1-/12 2024-01-12

2、时间戳转换2

在的时间戳格式使用pd.to_datetime()函数是无法识别的,需要用户根据原来的文本型时间戳格式在format参数中做出相应的格式设置。


import pandas as pd

l=[ "2021年3月3日 12时53分34秒","1971年4月1日 5时23分45秒" ]

# t=pd.Series(l).str.findall( "\d+" ).map( lambda l:l[0]+"-"+l[1]+"-"+l[2]+" "+l[3]+":"+l[4]+":"+l[5])

# t=pd.Series(l).str.findall( "\d+" ).map(lambda l:"{}-{}-{} {}:{}:{}".format(*l)) # 等同上行

t=pd.to_datetime(l,format= "%Y年%m月%d日 %H时%M分%S秒" )

print (t)

返回:

DatetimeIndex(['2021-03-03 12:53:34', '1971-04-01 05:23:45'], dtype='datetime64[ns]', freq=None)


import pandas as pd

l=[ 1,11339.3,33575 ]

t=pd.to_datetime(l)

t1=pd.to_datetime(l, origin = "1900-1-1" )

t2=pd.to_datetime(l, origin = "1900-1-1" , unit = "D" )

print (t)

print (t1)

print (t2)

返回:

DatetimeIndex(['1970-01-01 00:00:00.000000001',

'1970-01-01 00:00:00.000011339',

'1970-01-01 00:00:00.000033575'],

dtype='datetime64[ns]', freq=None)

DatetimeIndex([ '1900-01-01 00:00:00',

'1900-01-01 00:00:00.000011264',

'1900-01-01 00:00:00.000033536'],

dtype='datetime64[ns]', freq=None)

DatetimeIndex(['1900-01-02 00:00:00', '1931-01-18 07:12:00',

'1991-12-05 00:00:00'],

dtype='datetime64[ns]', freq=None)